var videosModel = require("../models/videos");
var videolabelModel = require("../models/videolabel");
var usersModel = require("../models/users");
var fs = require('fs')
var {createOne,updateOne,find}=require('../dao/base.js');
var commentsModel = require("../models/comments");
var path=require('path');
var defpath=path.join(__dirname,'../');



module.exports.upload =async (req, res) => {
  const files = req.files
  var fileList= []
  for(let i in files){
    var file = files[i]
    var filestatus = [];
    fs.renameSync(file.path,file.path+".mp4")
    fileList.push(file)
    var data = {
      src: file.path+".mp4",
      userid:req.query.userid
    }
    var doc = await createOne(videosModel, data);
    if (doc != null) {
      filestatus.push(`文件${file.path + ".mp4"}上传成功`);
      var docs2 =await updateOne(usersModel, { "userid": data.userid },
        { $addToSet: { "videos": doc._id } })
    } else {
      filestatus.push(`文件${file.path+".mp4"}上传失败`);
    }
  }
 res.sendResult(filestatus,200,"上传完成")
}

module.exports.download= (req,res) => {console.log(defpath + req.query.url);
  var path = defpath + req.query.url
  // var path="F:/ftproot/NW.js.docx";
  // var f = fs.createReadStream(path);

  res.setHeader('Content-type', 'application/octet-stream');
 res.setHeader('Content-Disposition', 'attachment;filename=*  .mp4');    // 'aaa.txt' can be customized.
  var fileStream = fs.createReadStream(path);
  fileStream.on('data', function (data) {
      res.write(data, 'binary');
  });
  fileStream.on('end', function () {
      res.end();
  })
 // res.writeHead(200, {
  //  'Content-Type': 'application/force-download',
  //  'Content-Disposition': 'attachment; filename=NW.js.mp4'
 // });
 // f.pipe(res);
  // var url = req.query.url
  // var subStr=new RegExp('/','i');//创建正则表达式对象,不区分大小写
  // var result=url.replace(subStr,"");//把'is'替换为空字符串
  // result?res.download(`${result}`):res.sendResult(null,403,"拒绝下载")
}

module.exports.getVideoLabel=async (req,res) => {
  var docs = await find(videolabelModel,{},'label');
  if(docs){
    return res.sendResult(docs,200,"请求视频标签成功")
  }
}

////获取视频评论列表
module.exports.getVideoComment = async (req, res) => {
  var page = req.query.page || 1
  let loginUserid = req.query.loginUserid
  var data = {
    total: 0,
    curPage: page,
    list: [],
    pageSize: 3
  }
  let videoid = req.params.videoid
  if (videoid) {
      var docs =await find(videosModel, { _id:videoid },'comments')
      var result2 = await find(commentsModel, { _id: { $in: docs[0].comments } },null,{
        skip: (page - 1) * data.pageSize,
        limit: data.pageSize,
        sort: { _id: -1 }
      },)
      var comments = new Array()
      if(loginUserid!==undefined){
        var loginUserLikeComments = await find(usersModel, { userid:loginUserid }, 'likeComments')
        //为评论结果加上子评论，是否点赞过，用户头像等字段
        for(let i=0;i<result2.length;i++){
          const res = await find(usersModel,{userid:result2[i].userid},['photo','name','baseUrl'])
          var index = loginUserLikeComments[0].likeComments.findIndex(v => result2[i]._id == v)+1
         comments.push({...result2[i]._doc,
          name:res[0].name,
          photo:res[0].photo,
          baseUrl:res[0].baseUrl,
          isLike:index?true:false,
        })
      }
      }else{
        for(let i=0;i<result2.length;i++){
          const res = await find(usersModel,{userid:result2[i].userid},['photo','name','baseUrl'])
         comments.push({...result2[i]._doc,
          name:res[0].name,
          photo:res[0].photo,
          baseUrl:res[0].baseUrl,
          isLike:false,
        })
      }
      }
  }
  res.sendResult(comments,200,`获取到${videoid}的评论`)
}

////获取回复的评论列表
module.exports.getReplyComment = async (req, res) => {
  let loginUserid = req.query.loginUserid
  var page = req.query.page || 1

  var data = {
    total: 0,
    curPage: page,
    list: [],
    pageSize: 3
  }
  let commentid = req.params.commentid
  if (commentid) {
      var docs =await find(commentsModel, { _id:commentid },'childComment')
      var childCommentList =await find(commentsModel, { _id: { $in: docs[0].childComment } },null, {
        skip: (page - 1) * data.pageSize,
        limit: data.pageSize,
        sort: { _id: -1 }
      },)
      var loginUserLikeComments = await find(usersModel, { userid:loginUserid }, 'likeComments')
       var childComment= new Array()
      //为子评论结果加上子评论，是否点赞过，用户头像等字段
       for(let j=0;j< childCommentList.length;j++){
         const res = await find(usersModel,{userid:childCommentList[j].userid},['photo','name','likeComments','baseUrl'])
         var index = loginUserLikeComments[0].likeComments.findIndex(v => childCommentList[j]._id == v)+1
         childComment.push({...childCommentList[j]._doc,
         name:res[0].name,
         photo:res[0].photo,
         baseUrl:res[0].baseUrl,
         isLike:index?true:false
           })
         }
  }
  res.sendResult(childComment,200,`获取到${commentid}的评论`)
}



